package com.mall.util;

import com.mall.domain.Car;
import com.mall.domain.Dict;
import com.mall.domain.ItemCat;
import com.mall.domain.ItemGoods;
import com.mall.domain.Member;
import com.mall.domain.Order;
import com.mall.domain.Permission;
import com.mall.domain.Role;
import com.mall.domain.RolePermission;
import com.mall.domain.User;
import com.mall.domain.UserRole;

import java.lang.reflect.Field;
import java.util.Locale;

public class CreateTable {
    public static void main(String[] args) {
        generateTableSql(UserRole.class);
    }
    private static void generateTableSql(Class obj) {
        String tableName;
        //获取类名User.class
        tableName = obj.getName();
        //User.class截取
        tableName = tableName.substring(tableName.lastIndexOf(".")+1);
        //驼峰式命名法
        Field[] fields = obj.getDeclaredFields();
        String column;
        StringBuilder sb = new StringBuilder();
        sb.append("drop table if exists ").append(tableName).append(";\r\n");
        sb.append("\r\n");
        sb.append("create table tb_").append(tableName.toLowerCase(Locale.ROOT)).append("(\r\n");
        /*System.out.println(tableName);*/
        for (Field f : fields) {
            column = f.getName();
            Class<?> type = f.getType();
            /*System.out.println(column + ","+type.getSimpleName());*/
            String typeName = type.getTypeName();
            sb.append(column);
            //这里只加了三种int date varchar 想要其他的自己加
            if ("java.lang.Integer".equals(typeName)) {
                sb.append(" int(11) ");
            } else if ("java.util.Date".equals(typeName)) {
                sb.append(" dateTime ");
            } else {
                sb.append(" varchar(255) ");
            }
            if ("id".equals(column)) {
                sb.append(" not null AUTO_INCREMENT ");
            }
            sb.append(",");
            sb.append("\n");
        }
        sb.append(" PRIMARY KEY (`id`)");
        String sql = sb.toString();
        sql = sb.substring(0,sql.length()) + "\n)" + "ENGINE = INNODB DEFAULT CHARSET = utf8mb4";
        System.out.println(sql);
    }
}
